package com.example.demo.service;

import com.example.demo.config.WechatConfig;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@RequiredArgsConstructor
@Service
@Slf4j
public class WechatService {

    private final WechatConfig wechatConfig;

    private static final String WECHAT_URL_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    private static final String WECHAT_URL_QRCODE = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s";

    public String getLoginQrCode(HttpSession httpSession) {
        String token = doGetAccessToken();
        return doGetQrCode(token);
    }


    private String doGetAccessToken() {
        String url = WECHAT_URL_TOKEN.formatted(wechatConfig.getAppid(), wechatConfig.getAppSecret());
        JsonNode response = new RestTemplate().getForObject(url, JsonNode.class);

        log.info("调用微信获取token接口，url：{}，response：{}", url, response);

        if (response.has("errcode")) {
            throw new RuntimeException("微信获取token出错");
        }

        // TODO
        int expiresIn = response.get("expires_in").asInt();

        return response.get("access_token").asText();
    }

    private void clearToken() {
        log.info("微信token手动清理");
    }

    private String doGetQrCode(String token) {
        String url = WECHAT_URL_QRCODE.formatted(token);

        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);

        ObjectNode objectNode = new ObjectMapper().createObjectNode();
        objectNode.put("expire_seconds", 604800);
        objectNode.put("action_name", "QR_SCENE");
        JsonNode scene = new ObjectMapper().createObjectNode().set("scene"
                , new ObjectMapper().createObjectNode().put("scene_id", 123));
        objectNode.set("action_info", scene);
        String body = objectNode.toString();

        HttpEntity<String> r = new HttpEntity<>(body, requestHeaders);

        ObjectNode response = new RestTemplate().postForObject(url, r, ObjectNode.class);

        log.info("调用微信获取ticket接口，url：{}， body：{}，response：{}", url, body, response);

        if (response.has("errcode")) {
            if (response.get("errcode").asInt() == 40001) {
                // token过期或者被覆盖
                clearToken();
                return doGetQrCode(doGetAccessToken());
            }
            throw new RuntimeException("微信获取token出错");
        }

        return response.get("ticket").asText();
    }

}
